<script lang="ts" setup>
import { useRouter } from 'vue-router'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { getActivityDetail, useGetActiveList, useUpdateActiveState } from '@fl/api/anjutong/seckill-manage'
import activityData from './components/activity-data.vue'
import { formatTime } from '@fl/utils'

const router = useRouter()

const activeId = ref('')
const initialState = {
    eventName: '', // 活动名称
    state: '',
    activeTime: '', // 活动时间
}

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const list = ref([])

const showDataVisible = ref(false)
const showHouseDataVisible = ref(false)
const houseDataList = ref([])
const queryParams = ref(cloneDeep(initialState))
const searchConditions = ref(cloneDeep(initialState))
const businessModulesList = ref([])
const columns = ref([
    {
        colProps: {
            span: 6,
        },
        label: '活动名称',
        prop: 'eventName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '状态',
        options: [
            {
                label: '进行中',
                value: 0,
            },
            {
                label: '已结束',
                value: 1,
            },
        ],
        prop: 'state',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            format: 'YYYY-MM-DD',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
        },
        label: '活动时间',
        prop: 'activeTime',
        valueType: 'date-picker',
    },
])

// 查询列表
const params = computed(() => ({
    eventName: searchConditions.value?.eventName ? searchConditions.value?.eventName : undefined,
    state: searchConditions.value?.state == 0 || searchConditions.value?.state == 1 ? searchConditions.value?.state : undefined,
    startTime: searchConditions.value.activeTime?.[0] ? formatTime(searchConditions.value?.activeTime[0], 'yyyy-MM-dd 00:00:00') : undefined,
    endTime: searchConditions.value.activeTime?.[1] ? formatTime(searchConditions.value?.activeTime[1], 'yyyy-MM-dd 23:59:59') : undefined,
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))
const { data, isLoading } = useGetActiveList(params)
watchEffect(() => {
    if (data.value) {
        list.value = cloneDeep(data.value.rows)
        tablePage.value.total = data.value.total
    }
})

const { mutate } = useUpdateActiveState()

function copyRow(row) {
    router.push(`/marketing-promotion/seckill-manage/seckill-active/seckill-active-add?type=copy&id=${row.id}`)
}

function showRow(row) {
    showDataVisible.value = true
    activeId.value = row.id
}

function showHouseData(row) {
    showHouseDataVisible.value = true
    getActivityDetail({ id: row.id }).then((res) => {
        if (res.code == 200) {
            houseDataList.value = res.data.details
        }
    })
}

function editRow(row) {
    router.push(`/marketing-promotion/seckill-manage/seckill-active/seckill-active-add?type=edit&id=${row.id}`)
}

function updateRowStatus(row) {
    // updateActiveState({
    //     eventId: row.eventId,
    //     state: row.state == 0 ? '0' : '1',
    // }).then((res) => {
    //     if (res.code == '200') {
    //         getDataList()
    //     }
    // })
    const params = {
        eventId: row.id,
        state: row.state == 0 ? '0' : '1',
    }
    mutate(params, {
        onSuccess: (res) => {
            console.log('res', res)
            const tips = row.state === 0 ? '已启用' : '已禁用'
            ElMessage({
                message: tips,
                type: row.state === 0 ? 'success' : 'info',
            })
        },
    })
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'eventId', minWidth: 200, title: '活动ID' },
        { field: 'eventName', minWidth: 200, title: '活动名称' },
        { field: 'spikeHouseCnt', minWidth: 200, slots: { default: 'spikeHouseCnt' }, title: '活动房源套数' },
        { field: 'spikeHouseCntOfSpike', minWidth: 200, slots: { default: 'spikeHouseCntOfSpike' }, title: '已秒杀房源套数' },
        { field: 'startTime', minWidth: 200, title: '活动开始时间' },
        { field: 'endTime', minWidth: 200, title: '活动结束时间' },
        { field: 'state', minWidth: 120, slots: { default: 'status' }, title: '状态' },
        { fixed: 'right', minWidth: 210, slots: { default: 'operate' }, title: '操作' },
    ],
})

// function getDataList() {
//     getActiveList({
//         // eventName: queryParams.value.eventName,
//         // startTime: queryParams.value.activeTime[0],
//         // endTime: queryParams.value.activeTime[1],
//         // state: queryParams.value.state,
//         pageNum: tablePage.value.currentPage,
//         pageSize: tablePage.value.pageSize,
//     }).then((res) => {
//         if (res.code == 200) {
//             list.value = res.rows
//             tablePage.value.total = res.total
//         }
//     })
// }

function resetSearch() {
    queryParams.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    tablePage.value.currentPage = 1
    // getDataList()
}

function submitSearch() {
    searchConditions.value = cloneDeep(queryParams.value)
    tablePage.value.currentPage = 1
    // getDataList()
}

function init() {
    // getDataList()
}

init()

// 分页组件变化
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    // getDataList()
}

// 跳转详情（新增、编辑）页面
function toPage(name, type, row) {
    const id = type === 'add' ? 'item' : row.id
    router.push({ name, params: { id, type } })
}
</script>

<template>
    <div>
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-model="queryParams"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            >
                <template #plus-field-plate>
                    <el-select v-model="plate">
                        <el-option v-for="item in businessModulesList"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value"
                                   :disabled="item.disabled"
                        />
                    </el-select>
                </template>
            </SearchForm>
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="list"
                         @page-change="handlePageChange"
            >
                <template #toolbar_buttons>
                    <el-button plain
                               type="primary"
                               @click="toPage('seckill-active-add', 'add')"
                    >
                        新增
                    </el-button>
                </template>

                <template #time="{ row }">
                    {{ row.startTime }} ~ {{ row.endTime }}
                </template>

                <template #spikeHouseCntOfSpike="{ row }">
                    <span>{{ row.spikeHouseCntOfSpike }}</span>
                </template>

                <template #spikeHouseCnt="{ row }">
                    <span class="color-red"
                          @click="showHouseData(row)"
                    >{{ row.spikeHouseCnt }}</span>
                </template>

                <template #status="{ row }">
                    <el-switch v-model="row.state"
                               :active-value="0"
                               :inactive-value="1"
                               @change="updateRowStatus(row)"
                    />
                </template>

                <template #operate="{ row }">
                    <div class="operate-btns">
                        <el-button type="primary"
                                   text
                                   @click="copyRow(row)"
                        >
                            复制
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="showRow(row)"
                        >
                            数据
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="editRow(row)"
                        >
                            编辑
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>

        <el-dialog v-model="showDataVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   title="数据"
                   width="1000"
                   modal-class="coupon-data-dialog"
                   draggable
        >
            <activityData :id="activeId"
                          name="coupon"
            />
        </el-dialog>

        <el-dialog v-model="showHouseDataVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   title="活动房源明细"
                   width="1100"
                   modal-class="coupon-data-dialog"
                   draggable
        >
            <el-table :data="houseDataList">
                <el-table-column prop="buildingName"
                                 label="楼盘名称"
                                 width="180"
                />

                <el-table-column prop="roomNo"
                                 label="房号"
                                 width="100"
                />

                <el-table-column prop="unitNo"
                                 label="单元"
                                 width="80"
                />

                <el-table-column prop="buildingNo"
                                 label="楼栋"
                                 width="80"
                />

                <el-table-column prop="floorNo"
                                 label="楼层"
                                 width="80"
                />

                <el-table-column prop="houseType"
                                 label="户型"
                                 width="120"
                />

                <el-table-column prop="area"
                                 label="面积（m2)"
                                 width="150"
                />

                <el-table-column prop="price"
                                 label="售价（元）"
                                 width="150"
                />

                <el-table-column prop="onePrice"
                                 label="一口价（元）"
                                 width="150"
                />
            </el-table>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.coupon-data-dialog {
}
:deep(.coupon-data-dialog .el-dialog) {
    max-height: calc(100vh - 80px) !important;
    overflow-y: auto;
}
:deep(.coupon-data-dialog .el-dialog__body) {
    overflow: hidden;
    overflow-y: auto;
}
.color-red {
    color: red;
}
</style>
